<template>
  <section id="index">
    <section class="top">
      <p>  <!-- {{$store.state}} -->
        <span v-show='false' v-if='lists.symbolList && lists.symbolList.length'>321</span> 
        <span>外汇</span>
        <span>商品 </span>
        <span>股票 </span> 
        <span>指数</span>
        <span>数字货币</span>
        <span>其他</span>
      </p>
      <h1>全方位投资首选</h1>
      <div>
        <span>专业</span>
        <span>安全</span>
        <span>高效</span>
      </div>
      <div>
        <div class="content">
          <div @click="toDown">
            <div class="left">
              <h2>APP下载</h2>
              <p>实时行情&nbsp;掌上交易</p>
            </div>
            <div class="right">
              <img src="../../assets/image/top1.png" alt="" width="100" height="90">
              <!-- <qrcode :value="url" :options="{ width: 64 }" id="qrcode"></qrcode> -->
            </div>
          </div>
          <div @click="toRecharge">
            <div class="left">
              <h2>USDT直购</h2>
              <p>开启充值新时代</p>
            </div>
            <div class="right">
              <img src="../../assets/image/top2.png" alt="" width="100" height="90">
            </div>
          </div>
          <div @click="$router.push('/announcement')">
            <div class="left">
              <h2>平台公告</h2>
              <p>重磅上线&nbsp;势如破竹</p>
            </div>
            <div class="right">
              <img src="../../assets/image/top3.png" alt="" width="100" height="90">
            </div>
          </div>
          <div @click="$router.push('/newPlayer')">
            <div class="left">
              <h2>新手指导</h2>
              <p>手把手教您玩转1805</p>
            </div>
            <div class="right">
              <img src="../../assets/image/top4.png" alt="" width="100" height="90">
            </div>
          </div>
        </div>
      </div>
    </section>
     <nav id='nav_container' style="overflow: hidden;"  class="notice">
       <div id='content' class="content">
         <a id="bulletin1" to="/noticeDetail/1" tag="a">
                 <BaseScorll v-if='notice1.length' :notice.sync='notice1'>
                </BaseScorll>
         </a>
         <a to="/noticeDetail/1" tag="a">
                 <BaseScorll v-if='notice2.length' :notice.sync='notice2'>
                </BaseScorll>
         </a>
         <a to="/noticeDetail/1" tag="a">
                 <BaseScorll v-if='notice3.length' :notice.sync='notice3'>
                </BaseScorll>
         </a>
        </div>
     </nav>

    <section class="list">
      <ul class="tab">
        <li  @click='tabIndex="自选"'  :class="tabIndex=='自选' ? 'active':''">自选</li>
        <li  @click='tabIndex="外汇"'  :class="tabIndex=='外汇' ? 'active':''">外汇</li>
        <li  @click='tabIndex="商品"'  :class="tabIndex=='商品' ? 'active':''">商品</li>
        <li  @click='tabIndex="指数"'  :class="tabIndex=='指数' ? 'active':''">指数</li>
        <li  @click='tabIndex="数字货币"'  :class="tabIndex=='数字货币' ? 'active':''">数字货币</li>
      </ul>
      <table>
        <thead>
          <tr>
            <th>产品名称</th>
            <th>最新价</th>
            <th>涨跌幅</th>
            <th>最高价</th>
            <th>最低价</th>
            <th>点差</th>
            <th>操作 </th>
           </tr>
        </thead>
        <tbody v-if='lists.symbolList && lists.symbolList.length && tabIndex!="自选"'>
          <tr  v-for="(item,i) in lists['symbolObj'][tabIndex]['goods_list'].length >=8 ? 8:lists['symbolObj'][tabIndex]['goods_list'].length" :key="item" > 
            <td >
               <img @click="addSymbol(lists['symbolObj'][tabIndex].goods_list[i].id)" 
                v-if="defaultSymbol.indexOf(lists['symbolObj'][tabIndex].goods_list[i].id)  ==-1  ?  true:false"
                src="../../assets/image/unselected.png" alt="" width="20" height="19">


               <img v-else @click="cancelSymbol(lists['symbolObj'][tabIndex].goods_list[i].id)" src="../../assets/image/selected.png" alt="" width="20" height="19">
              <!-- 商品标题 -->
              {{lists['symbolObj'][tabIndex].goods_list[i].goods_name}} 

              <!-- 商品code -->
              <span>({{lists['symbolObj'][tabIndex].goods_list[i]['goods_code']}})</span>
            </td>

              <!-- 最新价格 -->
            <td :class="{red:lists['symbolObj'][tabIndex].goods_list[i].inAndOut.zfType== 1,
                         green:lists['symbolObj'][tabIndex].goods_list[i].inAndOut.zfType== 2
                        }">{{lists['symbolObj'][tabIndex].goods_list[i].inAndOut.new_price}}</td>

              <!-- 涨幅 -->
            <td  :class="countUpsAndDowns(
                lists['symbolObj'][tabIndex].goods_list[i].inAndOut.new_price,
                lists['symbolObj'][tabIndex].goods_list[i].yest_close_price)>=0 ? 'red':'green'">

                {{ratioCalculate(lists['symbolObj'][tabIndex].goods_list[i].new_price,
                lists['symbolObj'][tabIndex].goods_list[i].yest_close_price)}}
                
              </td>  
              <!-- 最高价格 -->
            <td>{{lists['symbolObj'][tabIndex].goods_list[i].today_high_price}}</td>
            
              <!-- 最高低价格 -->
            <td>{{lists['symbolObj'][tabIndex].goods_list[i].today_low_price}}</td> 
            
              <!-- 点差 -->
            <td>{{lists['symbolObj'][tabIndex].goods_list[i].difference}}</td>
            
            <td @click='goDetial(lists.symbolObj[tabIndex].goods_list[i])'><img src="../../assets/image/exchange.png" alt="" width="18" height="18">
              去交易</td>
          </tr>
        </tbody>
        
         <!-- 自选 -->
        <tbody v-if='tabIndex=="自选" && lists[0].inAndOut.difference'>
        <tr  v-for="(item,i) in lists.length > 8 ? 8:lists.length "> 
            <td>  
               <!-- <img src="../../assets/image/unselected.png" alt="" width="20" height="19"> -->
               <img @click="cancelSymbol(lists[i].id)" src="../../assets/image/selected.png" alt="" width="20" height="19">
                
              <!-- 商品标题 -->
               {{lists[i].goods_name}}
              <!-- 商品code -->
              <span>({{lists[i].goods_code}})</span> 
            </td>
              <!-- 最新价格 -->
            <!-- <td  </td> -->
            <td  :class="{red:lists[i].inAndOut.zfType== 1,
                         green:lists[i].inAndOut.zfType== 2
                        }">{{lists[i].new_price}}</td>

              <!-- 涨幅 -->
            <td :class="countUpsAndDowns(
               lists[i].new_price,
                lists[i].yest_close_price)>=0 ? 'red':'green'" >

               {{ratioCalculate(lists[i].new_price,
               lists[i].yest_close_price)}}
         
              </td>  
              <!-- 最高价格 -->
            <td>{{lists[i].today_high_price}}</td>
            
              <!-- 最高低价格 -->
            <td>{{lists[i].today_low_price}}</td> 
            
              <!-- 点差 -->
            <td>{{lists[i].difference}}</td>
            
            <td @click='goDetial(lists[i])'><img src="../../assets/image/exchange.png" alt="" width="18" height="18">
              去交易</td>
          </tr>

        </tbody>
        
      </table>
      <div class="more">
        <span @click="goDetial('none',true)"> 查看更多
          <i class="triggle-down"></i>
        </span>
      </div>
    </section>
    <section class="info">
      <div class="title">
        <h2>全球领先的外汇金融服务商</h2>
        <h4>Global Leading Foreign Exchange Financial Service Providers</h4>
      </div>
      <div class="content">
        <div>
          <img src="../../assets/image/info1.png" alt="" width="170" height="170">
          <h3>系统保障</h3>
          <p>自主研发的核心交易引擎每秒处理百万笔交易保证交易快速高效，多层架构的设计大幅提高了系统的安全性、稳定性和扩展性</p>
        </div>
        <div>
          <img src="../../assets/image/info2.png" alt="" width="170" height="170">
          <h3>安全防护</h3>
          <p>1805技术团队具备丰富的安全系统打造经验，采用了先进的多层、多集群的系统架构打造专属顶尖安全风控体系和防护系统</p>
        </div>
        <div>
          <img src="../../assets/image/info3.png" alt="" width="170" height="170">
          <h3>专业服务</h3>
          <p>专业运营风控团队，用户至上，打造全新极致的体验，让交易在平台内高效、安全流通</p>
        </div>
      </div>
    </section>
    <section class="down clearfix" id="down">
      <div class="pull_left">
        <h2>多平台终端接入</h2>
        <h4>IOS、Android多平台支持全业务功能，指尖投资，掌上交易</h4>
        <div class="clearfix">
          <div class="pull_left">
            <img src="../../assets/image/ios.png" alt="" width="42" height="42">
            <span>IOS 下载</span>
          </div>
          <div class="pull_right">
            <img src="../../assets/image/andr.png" alt="" width="42" height="42">
            <span>Android 下载</span>
          </div>
        </div>
        <!-- <img src="../../assets/image/top1.png" alt="" width="120" height="120"> -->
        <qrcode :value="url" :options="{ width: 110 }" id="qrcode1"></qrcode>
        <p>扫码下载</p>
      </div>
      <div class="pull_right">
        <img src="../../assets/image/phone.png" alt="" width="155" height="283">
        <img src="../../assets/image/mac.png" alt="" width="613" height="362">
      </div>
    </section>
  <base-alert :bol.sync="alertBol" :type.sync="alertType"></base-alert>
  </section>
</template>
<script>
import {
    _getPNoticeList,
    _getSymbolTypeList,
    _getSymbolList,
    _getUserSymbolList,
    _getDefaultSymbolList,
    _addSymbolToUser,
    _deleteSymbolFromUser
    } from '../../axios/index.js'
import { setInterval } from 'timers';
import VueQrcode from '@chenfengyuan/vue-qrcode';
import { unlink } from 'fs';
export default {
  components: {
    "qrcode":VueQrcode
  },
  data() {
    return {
        // 切换商品
        tabIndex:'外汇', 
        defaultSymbol:[],
        userSymbol:[], //用户自选商品
        logoState:false,//登录状态
        notice1:[],
        notice2:[],
        notice3:[],
        alertType:1,//弹窗类型
        alertBol:false,// 弹窗
    }
  },
  created(){
       this.getSymbolTypeListAction();
       this.defaultSymbolList();
       this.getPNoticeList();
  },
  mounted(){
    let isAlet=JSON.parse(localStorage.getItem('isLodingAlert'))
              // localStorage.getItem('isLodingAlert')
     isAlet ? this.alterChoose(2):'';
     localStorage.setItem('isLodingAlert',false)
  },
  methods:{
    toDown() {
      this.$js.ScrollTop(document.getElementById('down').offsetTop,200);
    },
       //更改图表价格小数点
    getKlineFloat(newsPrice){
        //取小数
        let  lent=this.getFloat(newsPrice)
        //小数列表
        let  floatList=[100,10,100,1000,10000,100000,1000000,10000];
        //列表长度
        let  _flentg=floatList.length-1;
        //小数大于列表长度侧默认小数位数
        lent> _flentg ? lent=floatList[_flentg]:lent=floatList[lent]
        //缓存小数信息
        localStorage.setItem('pricescale',lent)
        //修改小数引用对象
        this.$store.state.pricescale.num=lent;
     },
     //获取公告
     async getPNoticeList(){
            // 请求数量
            let res= await _getPNoticeList(1,100);
            if(res.data.code==200){
              let data=res.data.data.data;
              for(let i=0;i<data.length;i++){
                   //文字过长处理
                   if(data[i].title.length>8){
                      let str=data[i].title.slice(0,7) + '...'
                      data[i].titles=str;
                      data[i].time=this.$js.timeToDate(data[i].create_time).slice(0,10);
                   }
                   //时间处理
                   else{
                      data[i].titles=  data[i].title;
                       data[i].time=this.$js.timeToDate(data[i].create_time).slice(0,10);
                   }
              }
            
              let _notice1=[],_notice2=[],_notice3=[],num=0;
              //第一组
             for(let i=0;i<2;i++){
               if(data[num]!=null){
                    _notice1.push(data[num])
               }
                 num++
             }
             //第二组
             for(let i=0;i<2;i++){
               if(data[num]!= undefined){
                 _notice2.push(data[num])
               }
                 num++
             }
             //第三组
             for(let i=0;i<2 ;i++){
                if(data[num]!= undefined){
                   _notice3.push(data[num])
               }
                 num++
             }
             this.notice1=_notice1;
             this.notice2=_notice2;
             this.notice3=_notice3;
           
            }
    },
     goDetial(item,bol){
       //查看更多
       if(bol){
          this.getKlineFloat('1.12569')
          localStorage.setItem('symbol','wh_eurusd');
          this.$store.state.traViewSymboId='wh_eurusd';
          this.$store.commit('setdetialTab',1)
          this.$router.push("/trade");
          return false;
       }
      //当前商品
        this.getKlineFloat(item.new_price)
        localStorage.setItem('symbol',item.system_code);
        this.$store.state.traViewSymboId=item.system_code;
        this.$store.commit('setdetialTab',item.type_id)
        this.$router.push("/trade");
        
        // this.$store.state.detialTab=this.tabIndex
     },
     alterChoose(type){
         this.alertType=type;
         this.alertBol=true;
     },
           // 用户添加自选
     async addSymbol(goods_id){
         const $store=this.$store.state
         let uid = $store.user 
         if(uid.id) {}
         else uid=localStorage.getItem('user') !=null ? localStorage.getItem('user').id:''
        //  if(!goods_id && !uid) return;
          if(uid==''){
              this.alterChoose(2)
              return;
        }
         const res = await _addSymbolToUser(uid.id,goods_id,{user:'loading'})
         if(res.data.code==200){
           this.defaultSymbol.push(goods_id)
           this.$Message.success(res.data.msg);
         }else{
           this.$Message.success(res.data.msg);
         }
         
     },
     // 用户取消自选
     async cancelSymbol(goods_id){
        const $store=this.$store.state
        let uid = $store.user 
        if(uid.id) {}
        else uid=localStorage.getItem('user') !=null ? localStorage.getItem('user').id:''
            if(uid==''){
              this.alterChoose(2)
              return;
        }
         //  if(!goods_id && !uid) return;
        const res = await _deleteSymbolFromUser(uid.id,goods_id,{user:'loading'});
        if (res.data.code === 200) {
            let data=[];
            let key=this.defaultSymbol.indexOf(goods_id);
            for(let i=0;i<this.defaultSymbol.length;i++){
                 if(i==key){
                     
                 }else data.push(this.defaultSymbol[i])
            }
           this.defaultSymbol=data;
           this.$Message.success(res.data.msg);
        }else{
           this.$Message.success(res.data.msg);
         }
    },
     // 系统默认推荐自选
     async defaultSymbolList(){
             let res=await _getDefaultSymbolList();
             let data=res.data.data
             for(let i=0;i<data.length;i++){
                 //系统默认 + 用户自选 
                 this.defaultSymbol.push(data[i])
             }
     },
     // 用户自选商品列表
     async getUserSymbolList(){
        const $store=this.$store.state
        if(!$store.user && !localStorage.getItem('token')){
           console.error('用户未登录请求用户自选列表失败')
           return;
        }
        let res=await _getUserSymbolList($store.user.id);
        if(res.data.code==200){
            let data=res.data.data;
            for(let i=0;i<data.length;i++){
                this.defaultSymbol.push(data[i])
                   //用户自选商品
                this.userSymbol.push(data[i])
            };
        }
      },
      // 计算涨幅
      ratioCalculate(price, yclose) {
          let bili = 0;
          if (Number(yclose) != 0) {
            bili = (
              ((Number(price) - Number(yclose)) / Number(yclose)) *
              100
            ).toFixed(2);
    
            if (bili > 0) {
              bili = "+" + bili;
            }
          }
         return bili + "%";
    },
     //计算涨跌
    countUpsAndDowns(newsPrice,closePrice){
      var maxPrice=(Number(newsPrice)-Number(closePrice)).toFixed(this.getFloat(closePrice,true));
      maxPrice=maxPrice>=0?'+'+maxPrice:maxPrice;
      return maxPrice;
    },
    //获取小数位数
    getFloat(val, bol) {
      let _self = this;
      let _default = bol ? 0 : 1;

      let maxVal =
        String(val).split(".").length == 2
          ? val.split(".")[1].length
          : _default; // 最小变化单位
      return maxVal;
    },
    //退出登录更改自选列表数据
    outRemUserSyb(data){
      this.defaultSymbol=data;
    },
    toRecharge() {
      if(this.user==null || this.user=='') {
        this.alterChoose(2)
      }
      if (this.user.is_agent != 1) {
        this.$router.push('/assets/usdt')
      } else {
        this.$Message.error('代理不能充值');
      }
    },
       // 触发获取商品类别列表的请求
   async getSymbolTypeListAction() {
       const $store = this.$store;
       let res = await _getSymbolTypeList();
       if (res.data.code == 200) {
           $store.state.symbolTypeList = res.data.data;
           // 商品详情列表的请求
           this.getSymbolListAction();
       } else console.error(`获取商品列表类型接口状态${res.data.code}`)
   },
   // 触发获取商品详情列表的请求
   async getSymbolListAction() {
       const $store = this.$store;
       let res = await _getSymbolList();
       if (res.data.code == 200) {
           $store.state.symbolList = res.data.data;
           for (const iterator of $store.state['symbolTypeList']) {
               //获取商品类型索引
               $store.state.symbolObj[iterator.type_name] = null;
           }
           for (const iterator of $store.state['symbolList']) {
               //为已有商品类型索引，存ru商品列表。
               $store.state.symbolObj[iterator.type_name] !== undefined ?
                   $store.state.symbolObj[iterator.type_name] = iterator : '';
          
           }
          

       } else console.error(`获取商品详情列表接口状态${res.data.code}`)

   },

  },
  watch:{
    
  },
  computed:{
      lists(){  // 监听商品对象
           let symbol=this.$store.state
            //登录成功
           if(symbol.user && symbol.token && !this.logoState){
              this.getUserSymbolList();
              this.logoState=!0;
           }
           //退出登录
           else if((!symbol.user || !symbol.token) &&  this.logoState && this.userSymbol.length){
              //用户自选列表数据
              this.$store.commit("setIsLogin", true);

              let data=[];
              //从渲染自选商品列表数组中,筛选出用户的自选商品。
              for(let i=0;i<this.defaultSymbol.length;i++){
                 const Index=this.userSymbol.indexOf(this.defaultSymbol[i])
                 if(Index==-1) {
                         data.push(this.defaultSymbol[i]);
                 }
              }
              //退出登录更改自选列表数据
              this.outRemUserSyb(data)
              this.logoState=0;
           };
           if(this.tabIndex!='自选')  return symbol
           else{
            //筛选出与自选商品数组一致的数据,
             let defSymb=this.defaultSymbol;
             let defSymblist=[];
             for(let i=0;i<symbol.symbolList.length;i++){
               const tabIndex=symbol.symbolList[i].type_name;
                   for(let j=0;j<symbol.symbolObj[tabIndex]['goods_list'].length;j++){
                      const symb=symbol.symbolObj[tabIndex]['goods_list'][j];
                      for(let k=0;k<defSymb.length;k++){
                           if(defSymb[k]==symb.id){
                                 defSymblist.push(symb)
                           }
                      }
                      
                      
                   }

             }
             return defSymblist
           }

         
      },
      user() {
        return this.$store.state.user;
      },
      url() {
        return window.server.axiosUrl + '/down.html';
      }

  }
}
</script>

